package com.wd.tw.server;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @className: WebSocketEndpoint
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2024/11/19
 **/

@Component
@ServerEndpoint("/ws/endpoint")  // WebSocket 服务端端点
public class WebSocketEndpoint {

    // 存储所有连接的客户端会话
    private static final Set<Session> sessions = new CopyOnWriteArraySet<>();

    // 当WebSocket连接建立时被调用
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("WebSocket Connected: " + session.getId());
    }

    // 当WebSocket收到消息时被调用
    @OnMessage
    public String onMessage(String message, Session session) {
        sessions.add(session);  // 将新连接的会话添加到集合中
        System.out.println("Received message: " + message);
        return "Echo: " + message;  // 回显客户端发送的消息
    }

    // 当WebSocket连接关闭时被调用
    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);  // 将关闭连接的会话从集合中移除
        System.out.println("WebSocket Closed: " + session.getId());
    }

    // 处理WebSocket发生的错误
    @OnError
    public void onError(Session session, Throwable throwable) {
        sessions.remove(session);  // 出现错误时移除该连接
        System.out.println("Error on WebSocket: " + throwable.getMessage());
    }

    // 发送消息给所有连接的客户端
    public static void sendToClient(String message) {
        for (Session session : sessions) {
            try {
                session.getBasicRemote().sendText(message);  // 发送消息
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
